package day_2022_9_to_12.Day;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
/**
 * @author haomin
 * @date 2022/09/05 11:09
 **/
public class Day3_1_Num652_FindDuplicateSubtrees {
    class Solution {
        List<TreeNode> res = new ArrayList<>();
        public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
            Map<String, Integer> map = new HashMap<>();
            dfs(root, map);
            return res;
        }
        private String dfs(TreeNode root, Map<String, Integer> map){
            if(root == null) return "#";
            String str = "";
            str = (root.val)+" "+ dfs(root.left, map)+ " " + dfs(root.right, map);
            if(map.getOrDefault(str, 0) == 1) res.add(root);
            map.put(str, map.getOrDefault(str, 0)+1);
            return str;
        }
    }
}